<script setup>
import { ref, computed ,onMounted} from 'vue';
import axios from "axios";
import {ElMessage} from "element-plus";
import {useCartStore} from "@/store/cartStore";
import {useRouter} from "vue-router";
const cartStore = useCartStore()
const router = useRouter();
// 计算属性判断是否是手机端
const isMobile = computed(() => window.innerWidth <= 768);

// 示例数据
const addressInfo = ref([]);

const newAddress = ref({
  userId:'',
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  address: '',
});

const selectedAddress = ref(addressInfo.value[0] || {});

const addAddressDialogVisible = ref(false);
const showAddressList = ref(false);

//获取当前用户的ID
const userInfo = sessionStorage.getItem('CurUser');
if (!userInfo) {
  ElMessage.error('请先登录');
}

const user = JSON.parse(userInfo);
const userId = user.userId;


// 获取用户收货地址
const fetchReceivers = async () => {
  try {
    const response = await axios.get('/dressup/order/receivers', {
      params: { userId }
    });
    console.log('Fetched receivers:', response.data); // 检查返回的数据
    addressInfo.value = response.data;  // 更新收货地址
    if (addressInfo.value.length > 0) {
      selectedAddress.value = addressInfo.value[0];  // 默认选择第一个地址
    }
  } catch (error) {
    console.error('Error fetching receivers:', error);
  }
};

const showAddAddressDialog = () => {
  addAddressDialogVisible.value = true;
};

const addAddress = async () => {
  // 检查必填项是否为空
  if (!newAddress.value.receiverName || !newAddress.value.receiverPhone || !newAddress.value.province || !newAddress.value.city || !newAddress.value.district || !newAddress.value.address) {
    // 如果有任何字段为空，弹出提示信息
    ElMessage.error('请完整填写收货地址信息');
    return;  // 阻止提交
  }
  // 克隆新地址数据
  const newAddr = { ...newAddress.value };

  const userInfo = sessionStorage.getItem('CurUser');
  if (!userInfo) {
    ElMessage.error('请先登录');
    return;
  }

  const user = JSON.parse(userInfo);

  newAddr.userId = user.userId;

  try {
    // 发送 POST 请求到后端，新增收货地址
    const response = await axios.post('/dressup/receiver/addNewAddress', newAddr);

    if (response.status === 200) {
      // 如果请求成功，更新本地的地址列表
      addressInfo.value.push(newAddr);
      fetchReceivers();
      selectedAddress.value = newAddr; // 设置新地址为当前选中的地址

      // 重置新地址的输入表单
      newAddress.value = {
        receiverName: '',
        receiverPhone: '',
        province: '',
        city: '',
        district: '',
        address: '',
      };

      // 关闭地址添加对话框
      addAddressDialogVisible.value = false;

      // 弹出成功提示信息
      ElMessage.success('新增收货地址成功');
    } else {
      // 如果响应状态不是 200，显示错误信息
      ElMessage.error('新增收货地址失败');
    }
  } catch (error) {
    // 捕获异常，打印错误信息
    console.error('添加地址时发生错误:', error);
    ElMessage.error('新增收货地址失败');
  }
};

const selectAddress = (item) => {
  // fetchReceivers();
  selectedAddress.value = item;
  showAddressList.value = false;
};

// 在组件挂载时请求收货地址
onMounted(async () => {

  if (userId) {
    await fetchReceivers();  // 获取用户的收货地址
  }

  // 获取并解析sessionStorage中的payList数据
  const storedPayList = sessionStorage.getItem("payList");
  if (storedPayList) {
    console.log("Stored payList:", storedPayList);  // Debugging line
    payList.value = JSON.parse(storedPayList);
  } else {
    console.log("No payList found in sessionStorage");  // Debugging line
  }

  console.log("payList after loading from sessionStorage:", payList.value);  // Debugging line

});

const payList = ref([]);

// 计算商品总价
const totalPrice = computed(() => {
  return payList.value.reduce((total, item) => {
    return total + (item.clPrice * item.clNum); // 商品小计
  }, 0);
});


const totalInfo = ref({
  totalPrice: totalPrice
});

// 创建订单
const createOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.error("请选择收货地址");
    return;
  }

  if (payList.value.length === 0) {
    ElMessage.error("购物车中没有商品");
    return;
  }

  const cartItemIds = payList.value.map(item => item.cartId);
  const isNewAddress = false; // 修改为实际逻辑
  const receiverId = selectedAddress.value.receiverId;
  const newReceiver = null;

  const requestData = {
    userId, // 替换为实际的用户ID
    cartItemIds,
    receiverId,
    isNewAddress,
    newReceiver,
  };
  console.log('selectedAddress',selectedAddress);
  console.log('requestData',requestData);

  try {
    const response = await axios.post('/dressup/order/create', requestData);
    let orderNoCurrent=0;

    if (response.status === 200) {
      ElMessage.success("订单创建成功");
      console.log("创建的订单信息：", response.data);
      orderNoCurrent = response.data.data.orderNo;
      console.log("当前订单号：",orderNoCurrent)

      payList.value.forEach(item => console.log(item.clNo));

      //删除购物车中的商品
      payList.value.forEach(item => cartStore.delCart(item.clNo));

    //  删除sesstionStorage中的payList数据
      sessionStorage.removeItem("payList");
      payList.value=[];

      //刷新购物车
      cartStore.getCartItems();

      try {
        // router.push({ name: 'Pay',query:{orderNo:orderNoCurrent} });
        router.push({name:'pay',params:{order_no: orderNoCurrent}});
      }catch (error){
        ElMessage.error("跳转支付页异常");
      }


    } else {
      ElMessage.error("订单创建失败，请重试");
    }
  } catch (error) {
    console.error("订单创建失败：", error);
    ElMessage.error("订单创建失败，请稍后重试");
  }
};

</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-main>
        <div class="outer">
          <div class="outer1">
            <h3>收货地址</h3>
            <div class="address-container" style="display: flex;justify-content: space-between;align-content: center;">
              <div v-if="selectedAddress" class="addressList" style="margin: 5px">
                <p>收货人：<span>{{selectedAddress.receiverName}}</span></p>
                <p>联系方式：<span>{{selectedAddress.receiverPhone}}</span></p>
                <p>收货地址：<span>{{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.district }} {{ selectedAddress.address }}</span></p>
              </div>
              <div v-else class="addressList" style="margin: 5px">
                暂无收货地址，请添加
              </div>
              <div class="action">
                <el-button size="large" @click="showAddressList = true">更改地址</el-button>
                <el-button size="large" @click="showAddAddressDialog">添加地址</el-button>
              </div>
            </div>
            <!-- 地址列表 -->
            <el-dialog v-model="showAddressList" title="选择地址" v-bind:width="isMobile ? '90%' : '30%'">
              <el-scrollbar wrap-class="address-scrollbar" view-class="address-scrollbar__view">
                <div class="address-list-container">
                  <div v-for="item in addressInfo" :key="item.id" class="address-item" @click="selectAddress(item)">
                    <p>收货人：{{ item.receiverName }}</p>
                    <p>联系方式：{{ item.receiverPhone }}</p>
                    <p>收货地址：{{ item.province }} {{ item.city }} {{ item.district }} {{ item.address }}</p>
                  </div>
                </div>
              </el-scrollbar>
            </el-dialog>

            <!-- 添加新地址的对话框 -->
            <el-dialog title="添加新地址" v-model="addAddressDialogVisible" v-bind:width="isMobile ? '90%' : '30%'">
              <el-form :model="newAddress">
                <el-form-item label="收货人">
                  <el-input v-model="newAddress.receiverName"></el-input>
                </el-form-item>
                <el-form-item label="联系方式">
                  <el-input v-model="newAddress.receiverPhone"></el-input>
                </el-form-item>
                <el-form-item label="省份">
                  <el-input v-model="newAddress.province"></el-input>
                </el-form-item>
                <el-form-item label="城市">
                  <el-input v-model="newAddress.city"></el-input>
                </el-form-item>
                <el-form-item label="区县">
                  <el-input v-model="newAddress.district"></el-input>
                </el-form-item>
                <el-form-item label="详细地址">
                  <el-input v-model="newAddress.address"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
              <el-button @click="addAddressDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addAddress">确 定</el-button>
            </span>
            </el-dialog>
          </div>

          <div class="outer1">
            <h3>商品信息</h3>
            <div v-if="payList.length > 0" class="goodsList" style="margin: 5px">
              <table>
                <thead>
                <tr>
                  <th>商品名称</th>
                  <th>单价</th>
                  <th>数量</th>
                  <th>小计</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="item in payList" :key="item.id">
                  <td>
                    <img :src="`http://localhost:8080/images/clothes/${item.clNo}.jpg`" alt="商品图片" class="product-image">
                    <span>{{ item.clName }}</span>
                  </td>
                  <td>¥{{ item.clPrice }}</td>
                  <td>{{ item.clNum }}</td>
                  <td>¥{{ (item.clPrice * item.clNum) }}</td>
                </tr>
                </tbody>
              </table>
            </div>
            <div v-else class="" style="margin: 5px">
              暂无商品信息
            </div>
          </div>
          <div class="outer1">
            <h3>金额明细</h3>
            <div class="totalInfoIner" style="margin: 5px">
              <div v-if="totalInfo" class="totalList" style="margin: 5px">
                <p>商品总价：
                  <span>￥{{ totalInfo.totalPrice }}</span>
                </p>
                <p>
                  运费：
                  <span>￥0</span>
                </p>
                <p>
                  应付总额：
                  <span>￥{{ totalInfo.totalPrice }}</span>
                </p>
              </div>
              <div v-else class="" style="margin: 5px">
                暂无金额明细
              </div>
            </div>
            <el-button type="primary" @click="createOrder" class="payButton">提交订单</el-button>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<style>
/*.h3{*/
/*  font-weight: bold;*/
/*}*/

.address-container {
  display: flex; /* 使用Flexbox布局 */
  justify-content: space-between; /* 两端对齐 */
  align-items: center; /* 垂直居中 */
  border: 1px solid #f0f0f0;
  margin-top: 10px;
  padding: 20px;
}

/*.address-scrollbar {*/
/*  max-height: 300px; !* 根据需要调整滑动条的最大高度 *!*/
/*}*/

.address-list-container {
  display: flex;
  flex-direction: column;
  padding: 10px; /* 内边距，可根据需要调整 */
}

.address-item {
  cursor: pointer;
  padding: 10px;
  border-bottom: 1px solid #eee; /* 地址项之间的分隔线 */
}

.address-item:last-child {
  border-bottom: none; /* 去掉最后一个地址项的底部分隔线 */
}
.address-item p{
  margin: 10px 0;
}

.outer{
  margin: 0px auto;
  background-color: white;
  padding: 20px 40px;
  width: 90%;
}
.payButton{
  border: #ffd2d8;
  background-color: #ff84b0;
  color: white;
}
.payButton:hover{
  background-color: #ffd2d8;
  color: #ff84b0;
}

.addressList p{
  color: #767676;
  margin: 10px 0;
}

.addressList p span{
  color: black;
}

.outer1{
  margin-bottom: 30px;
}

/*商品列表样式*/
.goodsList table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.goodsList table tr{
  line-height: 80px;
}

.goodsList th,
.goodsList td {
  padding: 8px;
  text-align: left;
}

.goodsList td{
  vertical-align: middle; /* 垂直居中 */
  border-bottom: 1px solid #ddd;
}

.goodsList th {
  background-color: #f9f9f9;
  font-weight: bold;
}

.goodsList p {
  margin: 5px 0;
}

.goodsList p span {
  color: black;
}

.product-image {
  width: 60px; /* 商品图片宽度 */
  height: 90px; /* 商品图片高度 */
  margin-right: 10px; /* 图片右边距 */
  vertical-align: middle;
  line-height: 60px;
}

/*.product-name {*/
/*  display: inline-block; !* 使名称和图片在同一行显示 *!*/
/*  align-content: center;*/
/*}*/

/*金额明细*/
.totalList p{
  margin: 10px 0;
}

.totalList{
  border: 1px solid #f0f0f0;
  margin-top: 10px;
  padding: 20px;
}

.totalList p span{
  color: #f56c6c;
  font-weight: bold;
}

/*响应式布局*/

/* 超小屏幕：手机，小于768px */
@media (max-width: 767px) {
  .outer {
    width: 100%;
    padding: 10px;
  }

  .address-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .payButton {
    width: 100%;
  }

  /* 在手机端隐藏商品名称列 */
  .goodsList th:nth-child(1),
  .goodsList td:nth-child(1) {
    display: none;
  }
}

/* 小屏幕：平板，大于等于768px */
@media (min-width: 768px) and (max-width: 991px) {
  .outer {
    width: 750px;
  }

  .address-container {
    flex-direction: row;
  }

  .payButton {
    width: 100%;
  }
}

/* 中等屏幕：桌面显示器，大于等于992px */
@media (min-width: 992px) and (max-width: 1199px) {
  .outer {
    width: 970px;
  }
}

/* 大屏幕：大桌面显示器，大于等于1200px */
@media (min-width: 1200px) {
  .outer {
    width: 1170px;
  }
}
</style>